﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace QueryGroupBuilder
{
    internal class FileApp
    {
        private List<string> GetPathes(int piecesCount, string path)
        {
            string dictionary = GetDictionary(path);
            string extFileName = GetExtFileName(path);
            string fileName = GetFileName(path);
            List<string> pathList = new List<string>();

            for (int i = 0; i < piecesCount; i++)
            {
                pathList.Add(dictionary + fileName + i.ToString() + "." + extFileName);
            }

            return pathList;
        }

        private string GetFileName(string path)
        {
            int indexStart = path.LastIndexOf(@"\");
            
            int indexEnd = path.LastIndexOf(@".");

            return path.Substring(indexStart+1, indexEnd - indexStart-1);

        }

        private string GetExtFileName(string path)
        {
            

            int indexEnd = path.LastIndexOf(@".");

            return path.Substring(indexEnd + 1, path.Length - indexEnd - 1);
        }

        private string GetDictionary(string path)
        {
            int indexStart = 0;

            int indexEnd = path.LastIndexOf(@"\");

            return path.Substring(indexStart, indexEnd+1);
        }

        private List<List<string>> DevidePieces(IList<string> strs, int piecesCount)
        {
            List<List<string>> lists = new List<List<string>>();

           

            for (int i = 0; i < piecesCount; i++)
			{
                lists.Add(new List<string>());
			}

            int pos = 0;
            foreach (string item in strs)
            {
                lists[pos].Add(item);
                pos++;
                if (pos==piecesCount)
                {
                    pos = 0;
                }
            }

            return lists;
        }

        private void SaveToFile(IList<string> strs, string path)
        {
            FileInfo myFile = new FileInfo(path);

            StreamWriter sw = myFile.CreateText();

            foreach (string s in strs)
            {
                sw.WriteLine(s);
            }
            sw.Close();
        }

        public bool SaveList(IList<string> strs, string path, int piecesCount)
        {
            try
            {
                

                List<string> pathes = GetPathes(piecesCount, path);

                List<List<string>> strsLists = DevidePieces(strs, piecesCount);

                for (int i = 0; i < piecesCount; i++)
                {
                    SaveToFile(strsLists[i], pathes[i]);
                }

                return true;
            }
            catch 
            {

                return false;
            }

        }

    }
}
